#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
轻量级网站访问器
使用 wget 命令访问网站，速度很快

依赖：系统已安装 wget
"""

import time
import random
import csv
import os
import subprocess
from datetime import datetime
import numpy as np

# ============= 配置区域（在这里修改参数） =================
CONFIG = {
    "URL": "https://blog.csdn.net/Zero_VPN/article/details/154238580?spm=1001.2014.3001.5501",
    "MAX_VISITS": 10000,
    "INTERVAL_MEAN": 5,
    "CSV_FILE": "visits_log_wget.csv",
}
# ========================================================

# 常见设备的 User-Agent 列表
USER_AGENTS = [
    # Desktop - Chrome
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    
    # Desktop - Firefox
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:121.0) Gecko/20100101 Firefox/121.0",
    
    # Desktop - Safari
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15",
    
    # Mobile - iPhone
    "Mozilla/5.0 (iPhone; CPU iPhone OS 17_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Mobile/15E148 Safari/604.1",
    
    # Mobile - Android
    "Mozilla/5.0 (Linux; Android 13; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.144 Mobile Safari/537.36",
]

def check_wget():
    """检查系统是否安装了 wget"""
    try:
        result = subprocess.run(["which", "wget"], capture_output=True, text=True)
        return result.returncode == 0
    except:
        return False

def get_log_file_path():
    """获取日志文件路径"""
    script_dir = os.path.dirname(os.path.abspath(__file__))
    logs_dir = os.path.join(script_dir, "logs")
    if not os.path.exists(logs_dir):
        os.makedirs(logs_dir)
    return os.path.join(logs_dir, CONFIG["CSV_FILE"])

def now_iso():
    """返回当前时间的 ISO 格式字符串"""
    return datetime.utcnow().isoformat() + "Z"

def get_poisson_interval(mean):
    """使用泊松分布生成访问间隔时间"""
    interval = np.random.exponential(mean)
    return max(2.0, interval)

def get_random_user_agent():
    """随机选择一个 User-Agent"""
    return random.choice(USER_AGENTS)

def write_csv_header(csvfile):
    """写入 CSV 文件头"""
    with open(csvfile, "a", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        if f.tell() == 0:
            writer.writerow([
                "timestamp_utc", 
                "visit_number", 
                "url", 
                "user_agent",
                "status_code",
                "response_time",
                "status", 
                "note"
            ])

def log_visit(visit_num, url, user_agent, status_code, response_time, status, note=""):
    """记录访问日志到 CSV"""
    log_file = get_log_file_path()
    with open(log_file, "a", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow([
            now_iso(),
            visit_num,
            url,
            user_agent,
            status_code,
            response_time,
            status,
            note
        ])

def visit_with_wget(url, user_agent):
    """使用 wget 访问页面"""
    try:
        # 创建临时文件
        temp_file = f"/tmp/wget_temp_{int(time.time())}_{random.randint(1000, 9999)}.html"
        
        cmd = [
            "wget", "-O", temp_file, "-q", "--timeout=30", "--tries=1",
            "--user-agent", user_agent,
            "--header", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
            "--header", "Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
            url
        ]
        
        start_time = time.time()
        result = subprocess.run(cmd, capture_output=True, text=True, timeout=35)
        response_time = round(time.time() - start_time, 2)
        
        # 清理临时文件
        if os.path.exists(temp_file):
            os.remove(temp_file)
        
        if result.returncode == 0:
            return {
                'success': True,
                'status_code': 200,  # wget 成功下载通常表示 200
                'response_time': response_time,
                'note': f'访问成功，耗时: {response_time}秒'
            }
        else:
            # 尝试从错误输出中提取状态码
            error_msg = result.stderr.lower()
            status_code = 0
            
            if "404" in error_msg:
                status_code = 404
            elif "403" in error_msg:
                status_code = 403
            elif "500" in error_msg:
                status_code = 500
            
            return {
                'success': False,
                'status_code': status_code,
                'response_time': response_time,
                'note': f'wget执行失败，返回码: {result.returncode}'
            }
            
    except subprocess.TimeoutExpired:
        return {
            'success': False,
            'status_code': 0,
            'response_time': 30,
            'note': '访问超时（30秒）'
        }
    except Exception as e:
        return {
            'success': False,
            'status_code': 0,
            'response_time': 0,
            'note': f'访问异常: {str(e)}'
        }

def main():
    """主函数"""
    print("🚀 开始轻量级访问任务")
    print(f"📍 目标 URL: {CONFIG['URL']}")
    print(f"🔢 最大访问次数: {CONFIG['MAX_VISITS']}")
    print(f"⏱️  平均间隔: {CONFIG['INTERVAL_MEAN']} 秒")
    
    # 检查 wget
    if not check_wget():
        print("❌ 错误：系统中未找到 wget")
        print("💡 请安装 wget: sudo apt install wget")
        return
    
    print("✅ wget 已就绪")
    print(f"💾 日志文件: {get_log_file_path()}")
    print("-" * 60)
    
    # 确保日志文件存在
    write_csv_header(get_log_file_path())
    
    visit_count = 0
    max_visits = CONFIG["MAX_VISITS"] if CONFIG["MAX_VISITS"] > 0 else float('inf')
    
    while visit_count < max_visits:
        visit_count += 1
        
        print(f"[访问 #{visit_count}]")
        
        # 随机选择 User-Agent
        user_agent = get_random_user_agent()
        print(f"  🌐 UA: {user_agent[:60]}...")
        
        # 访问页面
        result = visit_with_wget(CONFIG["URL"], user_agent)
        
        if result['success']:
            status = "✅ 成功"
            print(f"  {status}")
            print(f"  📊 {result['note']}")
        else:
            status = "❌ 失败"
            print(f"  {status}")
            print(f"  💥 {result['note']}")
        
        # 记录日志
        log_visit(
            visit_count, 
            CONFIG["URL"], 
            user_agent, 
            result['status_code'], 
            result['response_time'], 
            "成功" if result['success'] else "失败", 
            result['note']
        )
        
        # 如果不是最后一次访问，计算等待时间
        if visit_count < max_visits:
            wait_time = get_poisson_interval(CONFIG["INTERVAL_MEAN"])
            print(f"  ⏳ 等待 {wait_time:.1f} 秒后进行下一次访问...")
            time.sleep(wait_time)
        
        print()
    
    print("✅ 已完成所有访问")
    print(f"📊 总访问次数: {visit_count}")
    print(f"💾 日志已保存到: {get_log_file_path()}")

if __name__ == "__main__":
    main()